<?php
	
	namespace org\tekuna\framework\response\http;

	use org\tekuna\base\Tekuna;
	
	use org\tekuna\core\context\Context;

	use org\tekuna\framework\response\ResponseException;

	
	class ContentResponse extends AbstractHttpResponse {
		
		protected
			$sContentType,
			$sCharset = 'utf-8',
			$sContent = '',
			$bCompressOutput = true;

			
		public function __construct($sContent = '', $iStatus = 200, $sContentType = 'text/html') {
			
			$this -> appendContent($sContent);
			$this -> setStatus($iStatus);
			$this -> setContentType($sContentType);
		}

		public function sendHeaders() {

			// send Tekuna 'marker'
			header('X-Powered-By: ##APPLICATION_NAME## ##TEKUNA_VERSION##');
			
			// content headers
			header("Content-Type: $this->sContentType; charset=$this->sCharset");
			header("Content-Length: ". strlen($this -> sContent));
		}
		
	
		public function sendContent() {
			
			// encode to response charset
			$sEncoding = mb_detect_encoding($this -> sContent);
			
			if ($sEncoding === false) {
			
				throw new ResponseException("The encoding of the content could not be detected.");
			}
			else {
				
				Tekuna :: getLogger(__CLASS__) -> info("Detected encoding '$sEncoding' for the content. Converting to '$this->sCharset'.");
				$this -> sContent = mb_convert_encoding($this -> sContent, $this -> sCharset, $sEncoding);
			}

			// close all remaining open output buffers 
			while (ob_get_level() > 0) {
				
				ob_end_flush();
			}
			
			// start compression output handler
			if ($this -> bCompressOutput && extension_loaded('zlib')) {

				ob_start("ob_gzhandler");
			}
			else {

				ob_start();
			}
			
			// put the buffered content to the php output buffer
			echo $this -> sContent;

			// send the buffer
			ob_end_flush();
		}
		

		public function setContentType($sContentType) {
			
			$this -> sContentType = $sContentType;
		}
		
		public function getContentType() {
			
			return $this -> sContentType;
		}
		
		// TODO: perform encoding changes when setting another charset?
		public function setCharset($sCharset) {
			
			$this -> sCharset = $sCharset;
		}
		
		public function getCharset() {
			
			return $this -> sCharset;
		}
		
		public function setContent($sContent) {
			
			$this -> sContent = $sContent;
		}
		
		public function appendContent($sContent) {
			
			$this -> sContent .= $sContent;
		}
		
		public function getContent() {
			
			return $this -> sContent;
		}

		public function setCompressOutput($bCompressOutput) {
			
			$this -> bCompressOutput = $bCompressOutput;
		}
		
		public function isCompressOutput() {
			
			return $this -> bCompressOutput;
		}
	}
